package com.sudo.boot.service.sys.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.boot.starter.redis.component.RedisKeys;
import com.sudo.boot.base.constant.SsoConstant;
import com.sudo.boot.base.constant.enums.EnumMenuType;
import com.sudo.boot.mapper.sys.entity.SysMenu;
import com.sudo.boot.mapper.sys.entity.SysRole;
import com.sudo.boot.mapper.sys.mapper.SysRoleMapper;
import com.sudo.boot.satoken.util.SaRedisUtil;
import com.sudo.boot.threadpool.annotation.AsyncTask;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 执行Redis业务操作
 *
 * @author DayDayUp
 * @datetime 2023-11-11 17:41
 **/
@Slf4j
@Service
public class SysRedisService {
    @Resource
    private SaRedisUtil saRedisUtil;
    @Resource
    private SysRoleMapper sysRoleMapper;


    @AsyncTask
    public void removeMenuOfRole(String roleCode) {
        String roleMenu = RedisKeys.roleMenu(roleCode);
        saRedisUtil.del(roleMenu);
    }

    @AsyncTask
    public void removeButtonOfRole(String roleCode) {
        String roleButton = RedisKeys.roleButton(roleCode);
        saRedisUtil.del(roleButton);
    }

    @AsyncTask
    public void removeMenuOrButtonOfRole(SysMenu sysMenu,String roleCode) {
        if (EnumMenuType.M.getCode().equals(sysMenu.getMenuType())) {
            removeMenuOfRole(roleCode);
        } else if (EnumMenuType.B.getCode().equals(sysMenu.getMenuType())) {
            removeButtonOfRole(roleCode);
        }
    }

    @AsyncTask
    public void removeMenuOrButtonOfAllRole(SysMenu sysMenu) {
        List<SysRole> sysRoleList = sysRoleMapper.selectAll();

        if (EnumMenuType.M.getCode().equals(sysMenu.getMenuType())) {
            for (SysRole sysRole : sysRoleList) {
                removeMenuOfRole(sysRole.getRoleCode());
            }
        } else if (EnumMenuType.B.getCode().equals(sysMenu.getMenuType())) {
            for (SysRole sysRole : sysRoleList) {
                removeButtonOfRole(sysRole.getRoleCode());
            }
        }
    }

    @AsyncTask
    public void removeRoleStatus(String roleCode) {
        String roleStatus = RedisKeys.roleStatus(roleCode);
        saRedisUtil.del(roleStatus);
    }

    @AsyncTask
    public void removeUserStatus(String username) {
        SaSession saSession = StpUtil.getSessionByLoginId(username);
        if (Objects.nonNull(saSession)) {
            saSession.delete(SsoConstant.currUserStatus);
        }
    }
}
